package com.hrbxlh.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.DelayQueue;

/**
 * @author sy
 */
@Component
public class DelOverDueMemberListener implements ApplicationListener<ContextRefreshedEvent> {

    private Logger logger = LoggerFactory.getLogger(DelOverDueMemberListener.class);

    private static DelayQueue<DelOverDueMemberListTask> delayQueue = new DelayQueue<>();
    @Autowired
    @Qualifier("taskExecutorTwo")
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null){
            new Thread(() -> {
                logger.info("删除过期人员");
                while (true) {
                    try {
                        DelOverDueMemberListTask delOverDueMemberListTask = delayQueue.take();
                        threadPoolTaskExecutor.execute(delOverDueMemberListTask);
                    } catch (Exception e) {
                        logger.error(e.getMessage(), e);
                    }
                }
            }).start();
        }
    }

    public static DelayQueue<DelOverDueMemberListTask> getDelayQueue() {
        return delayQueue;
    }
}
